<?php
namespace app\api\logic;

use think\Db;
use think\Controller;
use app\api\model\TradePpa;
use app\api\model\BillPaypal;
use app\api\service\Paypalagree;

/**
 * Paypal 通过协议支付逻辑层
 * @author sam
 * Date 2019/07/17
 */
class AgreeLogic extends Controller
{
    // 请求支付
    public function payment($data)
    {
        // 实例化支付
        $pay = new Paypalagree();

        // 查询交易ID
        $bill = $this->findBill($data['user_id']);
        if ($bill) {
            $res = $pay->futurePay($bill['agreement_id']);
            if ($res == "success") {
                $result = $this->saveTrade($data['trade_id'], $bill['bill_id']);
                return $this->returnMsg(200, 1);
            }else{
                // 更新交易ID状态
                $this->delTrade($data['trade_id']);
                $this->saveBill($bill['bill_id']);
                return $this->returnMsg(109, 0, $res, $res['L_ERRORCODE0'], $res['L_LONGMESSAGE0']);
            }
        }

        // 第一次支付
        $res = $pay->requestAgreement($data['goods_amount'], $data['goods_unit'], $data['success'], $data['cancel']);
        // Request error
        if (is_array($res)) {
            $this->delTrade($data['trade_id']);
            return $this->returnMsg(107, 0, $res, $res['L_ERRORCODE0'], $res['L_LONGMESSAGE0']);
        }

        return $this->returnMsg(199);
    }

    // 同意协议后支付
    public function agreement($tradeId, $token, $playId)
    {
        if (empty($tradeId) || empty($token) || empty($playId)) {
            if (!empty($tradeId)) $this->delTrade($tradeId);
            return $this->returnMsg(104);
        }

        $data  = $this->getInfo($tradeId);
        // 执行付款
        $pay = new Paypalagree();
        $res = $pay->agreement($token, $playId, $data['goods_amount']);
        if (empty($res['referenceid'])) {
            $this->delTrade($tradeId);
            return $this->returnMsg(108);
        }

        $bill = $this->saveAgreementId($res['referenceid'], $data['user_id']);
        if ($bill) {
            // 更新交易记录
            $this->saveTrade($tradeId, $bill);
        }
        return $this->returnMsg(200, 1);
    }

    // 保存请求信息
    public function saveRequest($data)
    {

        $list = [
            'goods_title'   => $data['goods_title'],
            'goods_desc'    => $data['goods_desc'],
            'goods_amount'  => $data['goods_amount'],
            'goods_unit'    => $data['goods_unit'],
            'user_id'       => $data['user_id'],
        ];

        // 请求参数
        $list['request_ip']    = getClientIp();
        $list['request_param'] = serialize($data);
        $list['create_time']   = date("y-m-d H:i:s", time());

        // 保存数据库
        $insertId = Db::name('trade_ppa')->insertGetId($list);
        return $insertId;
    }

    public function delTrade($id)
    {
        $trade = new TradePpa;
        return $trade::where('trade_id', $id)->delete();
    }

    // 获取交易记录信息
    public function getInfo($id)
    {
        $trade = new TradePpa;
        return TradePpa::get($id);
    }

    // 更新交易记录表bill_id
    public function saveTrade($trade_id, $bill_id)
    {
        $trade = new TradePpa;
        $res   = $trade::where('trade_id', $trade_id)->update(['bill_id' => $bill_id, 'status' => 1]);
        return $res;
    }

    // 保存交易ID到数据库
    public function saveAgreementId($agreement, $userId)
    {
        $bill = new BillPaypal;
        $bill->agreement_id = $agreement;
        $bill->user_id      = $userId;
        $bill->create_time  = date("y-m-d H:i:s", time());
        $bill->save();

        return $bill->bill_id;
    }


    public function delAgreement($id)
    {
        $bill = new BillPaypal;
        return $bill::where('agreement_id', $id)->delete();
    }

    // 查询交易ID
    public function findBill($userId)
    {
        $bill = new BillPaypal;
        $info = $bill->where('user_id', $userId)->where('status', 1)->find();
        return $info;
    }

    // 更新交易ID状态
    public function saveBill($bill_id)
    {
        $bill = new BillPaypal;
        $res   = $bill::where('bill_id', $bill_id)->update(['status' => -1]);
        return $res;
    }


    /**
     * 接口输出
     *
     * @param      intval   $code     错误代码
     * @param      boolean  $status   请求结果
     * @param      array    $data     参数
     * @param      string   $apiCode  接口返回代码
     * @param      string   $apiMsg   接口返回信息
     *
     * @return     array    ( response )
     */
    public function returnMsg($code, $status = false, $data = [], $apiCode = '', $apiMsg = '')
    {
        $msg  = config("logic.paypal_agreement_msg");
        $data = [
            'result'   => empty($status)? "fail": "success",
            'code'     => $code,
            'message'  => $msg[$code],
            'api_code' => $apiCode,
            'api_msg'  => $apiMsg,
            'data'     => $data,
        ];

        return json($data);
    }


}
